using System.IO;
using System.Linq;
using System.Threading.Tasks;
using DailyPoetryX.AzureStorage.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace DailyPoetryX.AzureStorage {
    /// <summary>
    /// 保存收藏服务。
    /// </summary>
    public class SaveFavoriteBlob {
        /// <summary>
        /// 身份验证服务。
        /// </summary>
        private static IAuthenticationService _authenticationService;

        /// <summary>
        /// 授权服务。
        /// </summary>
        private static IAuthorizationService _authorizationService;

        /// <summary>
        /// 收藏存储。
        /// </summary>
        private static IFavoriteStorage _favoriteStorage;

        /// <summary>
        /// 保存收藏Blob。
        /// </summary>
        /// <param name="authenticationService">身份验证服务。</param>
        /// <param name="authorizationService">授权服务。</param>
        /// <param name="favoriteStorage">收藏服务。</param>
        public SaveFavoriteBlob(IAuthenticationService authenticationService,
            IAuthorizationService authorizationService,
            IFavoriteStorage favoriteStorage) {
            _authenticationService = authenticationService;
            _authorizationService = authorizationService;
            _favoriteStorage = favoriteStorage;
        }

        [FunctionName("SaveFavoriteBlob")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = null)]
            HttpRequest req, ILogger log) {
            log.LogInformation(
                "SaveFavoriteBlob HTTP trigger function processed a request.");

            var authenticationHelperResult =
                await AuthorizationHelper.Authorize(req, log,
                    _authenticationService, _authorizationService);
            if (!authenticationHelperResult.Passed) {
                return authenticationHelperResult.ActionResult;
            }

            var name = authenticationHelperResult.AuthenticationResult.Name;

            if (!req.ContentType.Contains("multipart/form-data") ||
                (req.Form.Files?.Count ?? 0) == 0) {
                log.LogInformation("No files found in request.");
                return new BadRequestResult();
            }

            var file = req.Form.Files.First();
            var memoryStream = new MemoryStream();
            await file.CopyToAsync(memoryStream);
            await _favoriteStorage.SaveAsync(memoryStream.ToArray(), name);
            return new NoContentResult();
        }
    }
}